package com.zhangjie.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.zhangjie.cmn.client.DictFeignClient;
import com.zhangjie.model.hosp.Hospital;
import com.zhangjie.repository.HospitalRepository;
import com.zhangjie.service.HospitalService;
import com.zhangjie.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired   //注入远程调用类
    private DictFeignClient dictFeignClient;

    //实现根据医院号查询
    @Override
    public Hospital getByHoscode(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        return hospital;
    }

    @Override//医院列表（条件分页查询）
    public Page<Hospital> selectHospPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        //创建pageable对象
        Pageable pageable = PageRequest.of(page - 1, limit);
        //创建条件匹配器
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        //hospitalQueryVo 转换 为hospital
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo,hospital);
        //创建对象
        Example<Hospital> example = Example.of(hospital, matcher);
        //调用hospitalRepository查询MongoDB数据库
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);
        //查询list集合，遍历封装医院等级
        pages.getContent().stream().forEach(item->{
            this.setHospitalHosType(item);
        });

        return pages;
    }

    @Override   //更新医院上线状态
    public void updateStatus(String id, Integer status) {
        Hospital hospital = hospitalRepository.findById(id).get();//先查找医院信息
        //设置修改的值
        hospital.setStatus(status);
        hospital.setUpdateTime(new Date());
        hospitalRepository.save(hospital);
    }

    @Override//查看医院信息
    public Map<String,Object> getHospById(String id) {
        Map<String, Object> map = new HashMap<>();
        Hospital temp = hospitalRepository.findById(id).get();//根据id查询医院信息
        Hospital hospital = this.setHospitalHosType(temp);  //放入查完字典的信息  封装了地址 医院等级 本来是没有的
        //医院的基本信息（包含等级）
        map.put("hospital",hospital);
        //单独处理预约信息
        map.put("bookingRule",hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        //返回
        return map;
    }

    @Override//根据医院名称得到医院名称
    public String getByHospName(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        if (hospital!=null){
            return hospital.getHosname();
        }
        return null;
    }

    @Override//根据医院名称查询
    public List<Hospital> findByHosname(String hosname) {
        //直接用spring data的命名规范
        return hospitalRepository.findHospitalByHosnameLike(hosname);
    }

    @Override//根据医院编号获取医院预约挂号详情
    public Map<String, Object> item(String hoscode) {
        Map<String, Object> map = new HashMap<>(); //创建返回对象
        Hospital hospital = this.getByHoscode(hoscode);//查询医院
        Hospital hospitalHosType = this.setHospitalHosType(hospital);//封装等级地址信息
        map.put("hospital",hospital);
        map.put("bookingRule",hospital.getBookingRule());//单独设置
        hospital.setBookingRule(null);
        return map;
    }


    //遍历封装医院等级，地址
    private Hospital setHospitalHosType(Hospital hospital) {
        //根据dictCode和value获取医院等级名称
        String hostypeString = dictFeignClient.getName("Hostype", hospital.getHostype());
        //查询省 市 地区
        String provinceString = dictFeignClient.getName(hospital.getProvinceCode());
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());
        hospital.getParam().put("hostypeString",hostypeString);
        hospital.getParam().put("fullAddress",provinceString+cityString+districtString);
        return hospital;
    }

    /**  保存医院调用的接口
     *   先判断mongodb有没有数据，再进行写入或修改     修改要结合数据库里面原来的字段 比如创建时间
     * @param map   前端传递过来的json数据
     */
    @Override
    public void save(Map<String, Object> map) {
        //把参数map集合装换成对象  Hospital
        String mapString = JSONObject.toJSONString(map);
        Hospital hospital = JSONObject.parseObject(mapString, Hospital.class);
        //判断是否存在数据
        String hoscode = hospital.getHoscode();
        Hospital hospitalExist=hospitalRepository.getHospitalByHoscode(hoscode);
        //如果不存在，就添加
        if (hospitalExist==null){
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }else {
            //存在，进行修改
            hospital.setStatus(hospitalExist.getStatus());
            hospital.setCreateTime(hospitalExist.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }
    }

}
